﻿import VTitle from '@/components/common/MainTitle.vue'
// 页面配置的弹窗
import TemplateSettings from '@/components/MetaFormComponents/MetaForm.vue'
// 页面预览的弹窗
import ShowMetaFormLayout from '@/components/MetaFormComponents/ShowMetaFormLayout.vue'
// 导入动态表单页面的组件
import ImportMethod from '@/components/common/TheImportMethod.vue'
// 导出动态表单页面的组件
import ExportMethod from '@/components/common/TheExportMethod.vue'
export default {
  components: {
    VTitle, TemplateSettings, ShowMetaFormLayout, ImportMethod, ExportMethod
  },
  data () {
    return {
      titleName: '移动端页面管理',
      tableData: [],
      // 一套系统只能有一个系统配置
      hadSystemPage: false,
      tableColumn: [
        {
          text: '名称',
          indexName: 'name'
        },
        {
          text: '类别',
          indexName: 'category'
        },
        {
          text: '是否出错',
          indexName: 'is_error'
        },
        {
          text: '是否警告',
          indexName: 'is_warnning'
        }
      ],
      // 编辑和新增的弹窗部分
      dialogTitle: '',
      dialogFormVisible: false,
      // 表单规则
      ruleForm: {
        uid: '',
        name: '',
        desc: '',
        settings: '',
        category: '',
        route: ''
      },
      labelWidth: '96px',
      operationType: '',
      rules: {
        name: [
          {required: true, message: '页面名称不能为空', trigger: 'blur'}
        ],
        category: [
          {required: true, message: '页面类别不能为空', trigger: 'change'}
        ]
      },
      // 检索内容
      searchInfo: {
        pageName: '',
        pageCategory: ''
      },
      // 保留输入的searchInfo
      saveSearchInfo: {
        pageName: '',
        pageCategory: ''
      },
      isSearch: false,
      // 页码部分
      totalData: [],
      filterData: [],
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      // 复制页面的部分
      copyLabelWidth: '120px',
      allCopyPages: [],
      copyFormVisible: false,
      copyRuleForm: {
        name: '',
        copyFormUid: '',
        desc: '',
        category: '',
        route: ''
      },
      copyRules: {
        name: [
          {required: true, message: '页面名称不能为空', trigger: 'blur'}
        ],
        copyFormUid: [
          {required: true, message: '复制的动态页面不能为空', trigger: 'change'}
        ],
        category: [
          {required: true, message: '页面类别不能为空', trigger: 'change'}
        ]
      },
      // 导入页面相关
      importPageInfo: {
        title: '导入移动端动态表单的脚本',
        apiRouter: '/d_form/script/import',
        dialog: false
      },
      // 导出相关的操作
      exportPageInfo: {
        title: '导出移动端动态表单的脚本',
        apiRouter: '/d_form/script/export',
        type: 'dynamicPage',
        dialog: false
      },
      // 页面配置的弹窗
      settingDialog: {
        dialogVisible: false,
        title: '',
        modal: false,
        opacity: 0
      },
      // 所有的元数据表
      allMetaTable: [],
      // 所有的事件
      allEvents: [],
      // 配置移动端页面的地址
      appSettingUrl: $URL.APP_SETTINGS_URL
    }
  },
  created () {
    // 页面开始加载时需要先加载iframe,通过修改modal和dialog的opacity的样式来给人没有展示的错觉
    this.settingDialog.dialogVisible = true
    this.getAllPages(1)
    // 获取所有的元数据表
    this.getAllMetaTable()
    // 获取所有的事件
    this.getAllEvents()
  },
  mounted () {
    // 获取iframe中的数据
    this.getIframeData()
  },
  methods: {
    // 获取所有的元数据表
    getAllMetaTable () {
      this.allMetaTable = []
      this.$get('/metadata').then(data => {
        let dataResult = data.data.result
        for (let i = 0; i < dataResult.length; i++) {
          this.addMetaTableToSameCategory(dataResult[i])
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 将相同的类别的元数据表放到一起
    addMetaTableToSameCategory (currentTable) {
      let hadPushed = false
      if (this.allMetaTable.length) {
        for (let i = 0; i < this.allMetaTable.length; i++) {
          // 如果有同类型的元数据表
          if (currentTable.category_no === this.allMetaTable[i].category_no) {
            this.$set(this.allMetaTable[i].tables, this.allMetaTable[i].tables.length, currentTable)
            hadPushed = true
            break
          }
        }
      }
      // 当没有同类型的元数据表时
      if (!hadPushed || !this.allMetaTable.length) {
        let obj = {
          category_name: currentTable.category_name,
          category_no: currentTable.category_no,
          tables: []
        }
        obj.tables.push(currentTable)
        this.$set(this.allMetaTable, this.allMetaTable.length, obj)
      }
    },
    // 获取所有的动态表单事件
    getAllEvents () {
      this.allEvents = []
      this.$get('/events4dform/alllist').then(data => {
        if (data.data.result.code === 'success') {
          this.allEvents = data.data.result.data
        } else if (data.data.result.code === 'failed') {
          this.$message({
            message: data.data.result.msg,
            type: 'warning'
          })
        }
      }).catch(error => {
        console.log(error)
      })
    },
    // 初始化表格的数据
    getAllPages (isLoad) {
      // 在检索的值清空前，先保存到变量saveSearchInfo中
      this.saveSearchInfo.pageName = this.searchInfo.pageName
      this.saveSearchInfo.pageCategory = this.searchInfo.pageCategory
      this.searchInfo = {
        pageName: '',
        pageCategory: ''
      }
      this.loading = true
      this.allCopyPages = []
      this.$get('/d_form', {
        type: 'app'
      }).then((data) => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.totalData = dataResult.data
          this.totalLength = dataResult.data.length
          // 在编辑或者是忽略警告、解决错误时，将检索的内容保存
          if (this.operationType === 'edit' || this.operationType === 'handleError'|| this.operationType === 'setting') {
            this.searchInfo.pageName = this.saveSearchInfo.pageName
            this.searchInfo.pageCategory = this.saveSearchInfo.pageCategory
            this.getSearchData()
          } else {
            // 调用方法进行页面渲染
            this.showData(this.totalData)
          }
          // 系统配置的页面只能有一个
          let dataHadSystemPage = false
          for (let i = 0; i < dataResult.data.length; i++) {
            if (dataResult.data[i].category !== 'systemPage') {
              this.$set(this.allCopyPages, this.allCopyPages.length, dataResult.data[i])
            } else {
              dataHadSystemPage = true
            }
          }
          this.hadSystemPage = dataHadSystemPage
          // 页面开始加载时需要先加载iframe,通过修改modal和dialog的opacity的样式来给人没有展示的错觉
          if (isLoad) {
            setTimeout(() => {
              this.settingDialog.dialogVisible = false
            }, 1000)
            setTimeout(() => {
              this.settingDialog.modal = true
              this.settingDialog.opacity = 1
              this.loading = false
            }, 1500)
          } else {
            this.loading = false
          }
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取指定页面的数据
    getCurrentPageInfo (uid) {
      this.loading = true
      this.$get('/d_form/' + uid).then((data) => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.loading = false
          this.ruleForm.name = dataResult.data.name
          this.ruleForm.desc = dataResult.data.desc
          this.ruleForm.settings = dataResult.data.settings
          this.ruleForm.category = dataResult.data.category
          this.ruleForm.route = dataResult.data.route
          this.ruleForm.uid = dataResult.data.uid
          // 编辑按钮时
          if (this.operationType === 'edit') {
            this.dialogFormVisible = true
          } else if (this.operationType === 'setting') {
            // 配置设定时
            let tittleName = dataResult.data.category === 'systemPage' ? (this.ruleForm.name) : (this.ruleForm.name + '--页面配置设定')
            this.$set(this.settingDialog, 'title', tittleName)
            this.$set(this.settingDialog, 'dialogVisible', true)
            let settingToIframe = {
              uid: dataResult.data.uid,
              category:  dataResult.data.category,
              pageName: dataResult.data.name, // 页面名称
              settings: dataResult.data.settings, // 页面的配置
              webOrigin: $URL.SYSTEM_SHOW_URL, // 系统的地址,iframe判断使用
              allDefinedPage: this.allCopyPages, // 所有的自定义页面---除去systemPage
              allEvents: this.allEvents, // 所有的事件
              allMetaTable: this.allMetaTable // 所有的元数据表
            }
            // 将数据传递到iframe中
            this.$refs.myIframe.contentWindow.postMessage(settingToIframe, '*')
          } else if (this.operationType === 'preview') {
            if (dataResult.data.settings) {
            } else {
              this.$message({
                message: '该动态模板还未进行配置设定，请先进行配置设定再预览',
                type: 'warning'
              })
            }
          }
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 点击预览的按钮
    handlePreview (row) {
      this.operationType = 'preview'
      this.getCurrentPageInfo(row.uid)
    },
    // 添加页面
    handleAdd () {
      this.dialogFormVisible = true
      this.dialogTitle = '添加移动端动态页面基本信息'
      this.ruleForm.uid = ''
      this.ruleForm.name = ''
      this.ruleForm.desc = ''
      this.ruleForm.settings = ''
      this.ruleForm.category = ''
      this.ruleForm.route = ''
      this.operationType = 'add'
    },
    // 编辑页面
    handleEdit (row) {
      this.dialogTitle = '编辑移动端动态页面基本信息'
      this.getCurrentPageInfo(row.uid)
      this.operationType = 'edit'
    },
    // 复制页面
    handleCopy () {
      this.copyFormVisible = true
      this.copyRuleForm.name = ''
      this.copyRuleForm.copyFormUid = ''
      this.copyRuleForm.desc = ''
      this.copyRuleForm.category = ''
      this.copyRuleForm.route = ''
    },
    // 删除页面
    handleDelete (row) {
      this.$confirm('此操作将永久删除该页面, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.operationType = 'delete'
        this.deleteMethod(row.uid)
      }).catch(() => {})
    },
    // 删除的方法
    deleteMethod (uid) {
      this.loading = true
      this.$delete('/d_form/' + uid).then((data) => {
        this.loading = false
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getAllPages()
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 提交编辑的方法
    submitEdit () {
      this.loading = true
      this.$patch('/d_form/' + this.ruleForm.uid, {
        name: this.ruleForm.name,
        desc: this.ruleForm.desc,
        settings: this.ruleForm.settings,
        template_uid: '',
        category: this.ruleForm.category,
        route: this.ruleForm.route,
        type: 'app'
      }).then((data) => {
        this.loading = false
        if (data.data.result.code === 'success') {
          // 当为配置设定时
          if (this.operationType === 'setting') {
            this.$set(this.settingDialog, 'dialogVisible', false)
            this.$message({
              message: '配置设定成功',
              type: 'success'
            })
          } else {
            // 编辑普通的信息时
            this.dialogFormVisible = false
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
          }
          this.getAllPages()
        } else {
          this.$message.error(data.data.result.msg)
        }
      })
    },
    // 提交新增的方法
    submitAdd () {
      this.$post('/d_form', {
        name: this.ruleForm.name,
        desc: this.ruleForm.desc,
        settings: this.ruleForm.settings,
        template_uid: '',
        category: this.ruleForm.category,
        type: 'app',
        route: this.ruleForm.route
      }).then((data) => {
        this.loading = false
        if (data.data.result.code === 'success') {
          this.dialogFormVisible = false
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.getAllPages()
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 点击新增或者编辑弹窗的确定按钮
    submitForm (forms, submitType) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          if (submitType === 'edit') {
            this.submitEdit()
          } else if (submitType === 'add') {
            this.loading = true
            this.submitAdd()
          }
        } else {
          return false
        }
      })
    },
    // 点击新增或者编辑弹窗的取消按钮
    resetForm (forms) {
      this.$refs[forms].clearValidate()
      this.dialogFormVisible = false
    },
    closeDialog () {
      this.$refs.ruleForm.clearValidate()
    },
    // 关闭复制页面的窗口
    closeCopyDialog () {
      this.$refs.copyRuleForm.clearValidate()
    },
    // 点击复制页面弹窗的取消按钮
    resetCopyForm (forms) {
      this.$refs[forms].clearValidate()
      this.copyFormVisible = false
    },
    // 点击复制页面弹窗确定按钮
    submitCopyForm (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          this.loading = true
          // 先获取关联到页面的详细
          this.$get('/d_form/' + this.copyRuleForm.copyFormUid).then((data) => {
            let dataResult = data.data.result
            if (dataResult.code === 'success') {
              var requestData = {
                name: this.copyRuleForm.name,
                desc: this.copyRuleForm.desc,
                settings: dataResult.data.settings,
                template_uid: '',
                category: this.copyRuleForm.category,
                route: this.copyRuleForm.route,
                type: 'app'
              }
              this.$post('/d_form', requestData).then((data) => {
                this.loading = false
                if (data.data.result.code === 'success') {
                  this.copyFormVisible = false
                  this.$message({
                    message: '复制成功',
                    type: 'success'
                  })
                  this.getAllPages()
                } else {
                  this.$message.error(data.data.result.msg)
                }
              }).catch((error) => {
                console.log(error)
              })
            } else {
              this.$message.error(data.data.result.msg)
              this.loading = false
            }
          }).catch((error) => {
            console.log(error)
          })
        } else {
          return false
        }
      })
    },
    // 将页码与数据关联
    showData (myData) {
      // 渲染表格的数据存放在 this.tableData 中
      this.tableData = []
      if (myData.length) {
        let from = (this.currentPage - 1) * this.pageSize
        let to = this.currentPage * this.pageSize
        if (to > myData.length) {
          to = myData.length
        }
        for (; from < to; from++) {
          this.tableData.push(myData[from])
        }
      }
    },
    // 底部页码的部分
    handleSizeChange (val) {
      this.pageSize = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    },
    handleCurrentChange (val) {
      this.currentPage = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    },
    // 配置设定
    handleSetting (row) {
      this.operationType = 'setting'
      this.getCurrentPageInfo(row.uid)
    },
    // 关闭配置页面的弹窗
    closeSettingDialog () {
      this.$confirm('确定放弃本次修改?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.$set(this.settingDialog, 'dialogVisible', false)
      }).catch(() => {})
    },
    // 获取iframe中的数据
    getIframeData () {
      window.addEventListener('message', e => {
        let fromURL = $URL.APP_SETTINGS_URL
        if ($URL.APP_SETTINGS_URL && $URL.APP_SETTINGS_URL.indexOf('/h5') !== -1) {
          fromURL = $URL.APP_SETTINGS_URL.slice(0, $URL.APP_SETTINGS_URL.indexOf('/h5'))
        }
        if (e.data && e.origin === fromURL) {
          if (e.data.closed === 'fail') {
            this.$set(this.settingDialog, 'dialogVisible', false)
          } else if (e.data.closed === 'success') {
            this.$set(this.ruleForm, 'settings', e.data.settings)
            this.submitEdit()
          }
        }
      })
    },
    // 忽略警告校正错位的按钮
    handleError (row, route) {
      let msg = route === 'correct' ? '确定该动态表单已修改正确，现进行校正？' : '忽略该动态表单的警告？'
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.loading = true
        this.operationType = 'handleError'
        this.$patch('/d_form/' + row.uid + '/' + route).then((data) => {
          this.loading = false
          if (data.data.result.code === 'success') {
            this.$message({
              message: data.data.result.msg,
              type: 'success'
            })
            this.getAllPages()
          } else {
            this.$message.error(data.data.result.msg)
          }
        })
      }).catch(() => {})
    },
    // 表格中的下拉菜单
    handleCommand (command) {
      switch (command.index) {
        case 2: {
          // 校正错误
          this.handleError(JSON.parse(command.rowData), 'correct')
          break
        }
        case 3: {
          // 忽略错误
          this.handleError(JSON.parse(command.rowData), 'ignore_warn')
          break
        }
        case 4: {
          // 删除
          this.handleDelete(JSON.parse(command.rowData))
          break
        }
      }
    },
    // 导入页面成功时
    finishedImportOperation () {
      this.importPageInfo.dialog = false
      this.$message({
        message: '导入移动端动态表单的脚本成功',
        type: 'success'
      })
      this.getAllPages()
    },
    // 获取搜索的数据
    getSearchData () {
      if (!this.searchInfo.pageCategory && !this.searchInfo.pageName) {
        this.pageSize = 10
        this.currentPage = 1
        this.totalLength = this.totalData.length
        this.isSearch = false
        // 调用方法进行页面渲染
        this.showData(this.totalData)
      } else {
        // 检索结果的数据存放在 this.filterData 中
        this.filterData = []
        this.totalData.forEach((value, index) => {
          if (this.searchInfo.pageName && this.searchInfo.pageCategory) {
            if (value.name.indexOf(this.searchInfo.pageName) >= 0 && value.category.indexOf(this.searchInfo.pageCategory) >= 0) {
              this.filterData.push(value)
            }
          } else if (this.searchInfo.pageCategory) {
            if (value.category.indexOf(this.searchInfo.pageCategory) >= 0) {
              this.filterData.push(value)
            } 
          } else if (this.searchInfo.pageName) {
            if (value.name.indexOf(this.searchInfo.pageName) >= 0) {
              this.filterData.push(value)
            } 
          }
        })
        this.isSearch = true
        this.currentPage = 1
        this.totalLength = this.filterData.length
        // 调用方法进行页面渲染
        this.showData(this.filterData)
      }
    }
  }
}
